package com.quick.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.quick.common.enums.HttpStatus;
import com.quick.common.result.CodeException;
import com.quick.gateway.properties.FilterProperties;
import com.quick.gateway.properties.TokenProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author 胡通达
 * @version 1.0
 * @date 2021-01-22 10:17
 */
@Component
@Setter
@Getter
@Slf4j
@EnableConfigurationProperties({FilterProperties.class, TokenProperties.class})
public class JwtTokenFilter implements GlobalFilter, Ordered {

    @Resource
    private FilterProperties filterProperties;
    @Resource
    private TokenProperties tokenProperties;


    /**
     * 过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        //判断白名单
      /*  if (!isAllowPath(url)) {
            return chain.filter(exchange);
        }
        //获取token
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");

        ServerHttpResponse resp = exchange.getResponse();
        if (StringUtils.isBlank(token)) {
            //没有token
            throw new CodeException(HttpStatus.UN_KNOW_ERROR);
        }*/
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    /**
     * 判断请求URI是不是白名单中的URI
     *
     * @param requestURI
     * @return
     */
    private Boolean isAllowPath(String requestURI) {
        boolean flag = false;
        for (String allowPath : filterProperties.getAllowPaths()) {
            if (requestURI.startsWith(allowPath)) {
                //允许
                flag = true;
                break;
            }
        }
        return flag;
    }


}
